import {
  request
} from "../../request/index.js"
import regeneratorRuntime from "../../lib/runtime/runtime.js"

// 事件分析 点击轮播图预览大图  调用小程序的api previewImage
Page({

  /**
   * 页面的初始数据
   */
  data: {
    GoodsObj: {},
    isCollect:false
  },
  //商品对象
  GoodsInfo: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    //先拿到当前的页面栈
    let pages = getCurrentPages();
    let currentPages = pages[pages.length - 1];
    let options = currentPages.options;
    const {
      goods_id
    } = options;
    this.getGoodsDetail(goods_id)
  },

  //获取商品的详情数据
  async getGoodsDetail(goods_id) {
    const goodsObj = await request({
      url: 'goods/detail',
      data: {
        goods_id
      }
    });
    this.GoodsInfo = goodsObj;
    //获取缓存中的商品收藏数组
    let collect =wx.getStorageSync("collect")||[];
    let isCollect=collect.some(ele=>ele.goods_id===this.GoodsInfo.goods_id)
    this.setData({
      GoodsObj: {
        goods_name: goodsObj.goods_name,
        goods_price: goodsObj.goods_price,
        goods_introduce: goodsObj.goods_introduce.replace(/\.webp/g, '.jpg'),
        pics: goodsObj.pics
      },
      isCollect
    })
  },
  // 点击轮播图预览大图 
  handlePreviewImage(e) {
    //先构造要预览的图片数组
    const urls = this.GoodsInfo.pics.map(e => e.pics_mid);
    const current = e.currentTarget.dataset.url;
    wx.previewImage({
      current,
      urls
    });

  },
  handleCartAdd() {
    //获取缓存中的购物车数组
    let cart = wx.getStorageSync("cart") || [];
    //判断商品对象是否存在于购物车数组中
    let index = cart.findIndex(v => v.goods_id === this.GoodsInfo.goods_id);
    if (index === -1) {
      //商品不存在  第一次添加
      this.GoodsInfo.num = 1;
      this.GoodsInfo.checked = true;
      cart.push(this.GoodsInfo)
    } else {
      //已经存在于购物车数据中，执行num+=
      cart[index].num++;
    }
    //把购物车重新添加回缓存中
    wx.setStorageSync("cart", cart);
    //弹窗提示
    wx.showToast({
      title: '加入购物车成功',
      icon: 'success',
      //防抖
      mask: true
    });

  },
    //点击收藏
    handleCollect(){
      console.log("123");
      let isCollect=false;
      //判断该商品是否存在于缓存的数组之中
      let collect=wx.getStorageSync("collect")||[];
      let index=collect.findIndex(ele=>ele.goods_id===this.GoodsInfo.goods_id);
      //已经存在把该商品删除
      if(index!==-1){
        collect.splice(index,1);
        isCollect=false;
        wx.showToast({
          title: '取消收藏成功',
          icon: 'success',
          mask: true
        });
      }else {
        //没有存在把该商品添加到收藏数组中  存入到缓存中即可
        collect.push(this.GoodsInfo);
        isCollect=true;
        wx.showToast({
          title: '收藏成功',
          icon: 'success',
          mask: true
        });
      }
      //把数组重新存入到数组中
      wx.setStorageSync("collect", collect);
      //修改data中的属性  isCollect;
      this.setData({
        isCollect
      })
    }
  
})